/*
 * Class: Friend Action Manager
 * author: Zaki Ullah
 * Company: Gaminations Inc.
*/

//GALocalizationHandler.getRelativeString(Core.Localization.getString("TZ_MESSAGE_OFFERS_COINS_BUCKS"),[totalCoinsDiff,totalBucksDiff]);
exports.MMFriendActionManager = Core.Class.singleton({
	
	classname: 'MMFriendActionManager',
	
	initialize: function()
	{
		this._allNeighborActions = null;
		this._friendCoinCollectedCount = 0;
		this._hasStolenCustomers = false;
		this._myStolenCustomerCount = 0;
		this._stolenCustomers = 0;
		this._allNeighborActions = GAGameLoader.getResponseObject().getNeighborActions();
		this.removeGiftsFromServer();
	},
	
	getAllNieghborActionsArray: function()
	{
		return this._allNeighborActions;
	},
	
	addMoreNeighborActions: function()
	{
		if(this._allNeighborActions && this._allNeighborActions.length > 0)
		{
			var friendsHelpCount = 0;
			var newGiftsCount = 0;
			var coinsReceived = 0;
			var stolenCustomerCount = 0;
			var alert = false
			var message = null;
			for (var i = 0; i < this._allNeighborActions.length; i++)
			{
				if(this._allNeighborActions[i].actiontype == kNeighborActionType.kNeighborActionTypeSendGift)
				{
					MMGameState.getCurrentUser().addGift(this._allNeighborActions[i]);
					newGiftsCount++;
				}
				else if(this._allNeighborActions[i].actiontype == kNeighborActionType.kNeighborActionTypeCollectCoinOrTrash)
				{
					coinsReceived = coinsReceived + this._allNeighborActions[i].amount;
					friendsHelpCount++;
				}
				else if(this._allNeighborActions[i].actiontype == kNeighborActionType.kNeighborActionTypeStealCustomers)
				{
					//console.log("zaki:::::: FRIEND STEAL SUCCESSFULLLL");
					
					stolenCustomerCount = stolenCustomerCount + parseInt(this._allNeighborActions[i].amount); 
				}
			}
			this._myStolenCustomerCount = stolenCustomerCount;
			//console.log("zaki:::::: MMGameState.getCurrentUser()"+MMGameState.getCurrentUser());
			MMGameState.getCurrentUser().updateCurrency(kOperationType.kOperationAddCoins,+coinsReceived);
			//updateCurrency(kOperationType.kOperationAddCoins,parseInt(currencyToAward))
//			
//			console.log("zaki:::::: friendsHelpCount "+friendsHelpCount);
//			console.log("zaki:::::: coinsReceived "+coinsReceived);
//			console.log("zaki:::::: newGiftsCount "+newGiftsCount);
//			
			if(newGiftsCount > 0 && friendsHelpCount > 0)
			{
				alert = true;
				message = GALocalizationHandler.getRelativeString(Core.Localization.getString("FRIEND_HELPED_COIN_GIFT_RECEIVED"),[newGiftsCount,coinsReceived]);
//				message =  "Hey you have received "+newGiftsCount+"gift(s) and "+coinsReceived+"coin(s) because your friends helped you out help them back.";
			}
			else if(newGiftsCount > 0 && friendsHelpCount == 0)
			{
				alert = true;
				message = GALocalizationHandler.getRelativeString(Core.Localization.getString("FRIEND_HELPED_GIFT_RECEIVED"),[newGiftsCount]);
				//message = "Hey you have received "+newGiftsCount+"gift(s) by your friends."
			}
			else if(friendsHelpCount > 0 && newGiftsCount == 0)
			{
				alert = true;
				message = GALocalizationHandler.getRelativeString(Core.Localization.getString("FRIEND_HELPED_COIN_RECEIVED"),[coinsReceived]);
				//message = "Hey you have received "+coinsReceived+"coin(s) because your friends helped you out help them back."
			}
			if(alert)
			{
				var alertBox = UIFactory.getAlertBox(Core.Localization.getString("MESSAGE"), message, ["ok"], this);
			}
			
			if(stolenCustomerCount > 0)
			{
				this.checkAndShowAlertForStolenCustomers();
			}
			
		}
	},
	
	removeGiftsFromServer: function()
	{
		var url = GAConfigurations.getURL();
		var gamerTag = GAConfigurations.getRecordID();

		url = url + "users/delete_naction?unique_id="+gamerTag;

		var webFetcher = new GAWebFetcher(this,30,0);
		webFetcher.tag = 2;
		webFetcher.invokeGetRequest(url);
	},
	
	getStolenCustomerCount: function()
	{
		return this._myStolenCustomerCount; 
	},
	
	setStolenCustomerCount: function(count)
	{
		this._myStolenCustomerCount = count;
	},
	
	checkAndShowAlertForStolenCustomers: function()
	{
		if(this._myStolenCustomerCount > 0)
		{
			var message = GALocalizationHandler.getRelativeString(Core.Localization.getString("MY_CUSTOMERS_STOLEN_ALERT"),[this._myStolenCustomerCount]);
			var alertBox = UIFactory.getAlertBox(Core.Localization.getString("MESSAGE"), message, ["ok"], this);
			this._myStolenCustomerCount = 0;	
		}
	},
	
	webFetchSuccess : function(webFetcher, responseData)
	{
		if(webFetcher.tag == 2)
		{
			this.addMoreNeighborActions();
			this.postGameState();
		}
		
		if(webFetcher.tag == 3)
		{
			
		}		

		if(webFetcher != null){
			webFetcher.destroy();
			webFetcher = null;
		}
	},
	
	webFetchFailure : function(webFetcher, errorCode)
	{	
//		var errorMsg = "MMFriendActionManager::webFetchFailure() responseStatusCode = > " + errorCode ;
//		GALogger.logWithLevel(errorMsg,LOG_LEVEL.LOG_NONFATAL_ERROR);
		if(webFetcher.tag == 2)
		{
			//var alertBox = UIFactory.getAlertBox("Message", "Gift sending failure please try again.", ["ok"], this);
		}
		
		if(webFetcher.tag == 3)
		{
		
		}
		
		if(webFetcher != null){
			webFetcher.destroy();
			webFetcher = null;
		}
	},
	
	postGameState: function()
	{
		var fileNames = GAConfigurations.getDbFileNames();
		GAGameStatePostHandler.postGameState(this,fileNames,"0",GAGameLoader._userXp);
	},
	
	sendGiftToFriend: function(giftJSON)
	{
		var friend = MMFriendManager.getVisitingFriendObj();
		var finalGiftJSON = JSON.stringify({"data":[giftJSON]});
		var gamerTag = friend.id;
		//gamerTag = "55605";	//TODO TESTING REMOVE LATER	
		var url = [];
		url.push(GAConfigurations.getURL());
		url.push("users/add_naction?unique_id=");
		url.push(gamerTag);
		url.push("&act_json="+finalGiftJSON);
		
		url = encodeURI(url.join(""));
		
		var webFetcher = new GAWebFetcher(this,30,0);
		webFetcher.tag = 1;
		webFetcher.invokeGetRequest(url);
	},
	
	gameStatePostSuccess: function(){
		console.log('>>gameStatePostSuccess');
	},
	gameStatePostFailure: function(error){	
		//this._delegate.gameStateFailure('>>gameStatePostFailure with error = '+error);
		//this.postGameState();
	},
	
	getFriendCoinActionState: function(friendId)
	{
		var friendsCoinsActionsList = MMStorageManager.getValueFromUserDefault("actionCoinCollected");
		
		if(friendsCoinsActionsList)
		{
			friendsCoinsActionsList = friendsCoinsActionsList+"";

			var friendsData = friendsCoinsActionsList.split("|");

			var friendsArray = [];
			for(var i = 0; i < friendsData.length; i++)
			{
				friendsArray[i] = friendsData[i].split(",");
			}
			for(var i = 0; i < friendsArray.length; i++)
			{
				var friend = friendsArray[i];
				if(friend[0] == friendId)
				{
					return friend;
				}
			}
			return null;
		}
		return null;
	},
	
	saveFriendCoinActionState: function(friendData)
	{
		var friendArray = friendData;
		var friendsCoinsActionsList = MMStorageManager.getValueFromUserDefault("actionCoinCollected");
		if(friendsCoinsActionsList)
		{
			friendsCoinsActionsList = friendsCoinsActionsList+"";
			var friendsData = friendsCoinsActionsList.split("|");
			var friendsArray = [];
			var saved = false;
			
			for(var i = 0; i < friendsData.length; i++)
			{
				friendsArray[i] = friendsData[i].split(",");
			}
			for(var i = 0; i < friendsArray.length; i++)
			{
				var friend = friendsArray[i]
				if(friend[0] == friendData[0])
				{
					friendsArray[i] = friendData;
					saved = true;
					break;
				}
			}
			if(!saved)
			{
				friendsArray.push(friendData);
				saved = true;
			}
			var temp = [];
			if(saved)
			{
				for(var i = 0; i <friendsArray.length; i++)
				{
					var tempData = friendsArray[i].join(",");
					temp.push(tempData);
				}
				var finalString = temp.join("|");
				MMStorageManager.saveToUserDefault("actionCoinCollected", finalString);
			}
		}
		else
		{
			MMStorageManager.saveToUserDefault("actionCoinCollected", friendData);
		}
	},
	
	getFriendTrashActionState: function(friendId)
	{
		var friendsCoinsActionsList = MMStorageManager.getValueFromUserDefault("actionTrashCollected");
		
		if(friendsCoinsActionsList)
		{
			friendsCoinsActionsList = friendsCoinsActionsList+"";

			var friendsData = friendsCoinsActionsList.split("|");

			var friendsArray = [];
			for(var i = 0; i < friendsData.length; i++)
			{
				friendsArray[i] = friendsData[i].split(",");
			}
			for(var i = 0; i < friendsArray.length; i++)
			{
				var friend = friendsArray[i];
				if(friend[0] == friendId)
				{
					return friend;
				}
			}
			return null;
		}
		return null;
	},
	
	saveFriendTrashActionState: function(friendData)
	{
		var friendArray = friendData;
		var friendsCoinsActionsList = MMStorageManager.getValueFromUserDefault("actionTrashCollected");
		if(friendsCoinsActionsList)
		{
			friendsCoinsActionsList = friendsCoinsActionsList+"";
			var friendsData = friendsCoinsActionsList.split("|");
			var friendsArray = [];
			var saved = false;
			
			for(var i = 0; i < friendsData.length; i++)
			{
				friendsArray[i] = friendsData[i].split(",");
			}
			for(var i = 0; i < friendsArray.length; i++)
			{
				var friend = friendsArray[i]
				if(friend[0] == friendData[0])
				{
					friendsArray[i] = friendData;
					saved = true;
					break;
				}
			}
			if(!saved)
			{
				friendsArray.push(friendData);
				saved = true;
			}
			var temp = [];
			if(saved)
			{
				for(var i = 0; i <friendsArray.length; i++)
				{
					var tempData = friendsArray[i].join(",");
					temp.push(tempData);
				}
				var finalString = temp.join("|");
				MMStorageManager.saveToUserDefault("actionTrashCollected", finalString);
			}
		}
		else
		{
			MMStorageManager.saveToUserDefault("actionTrashCollected", friendData);
		}
	},
	
	postFriendActionsDone: function()
	{
		var amount = this._friendCoinCollectedCount;
		var friend = MMFriendManager.getVisitingFriendObj();
		var giftJSON1 = null;
		var giftJSON2 = null;
		var finalGiftJSON = null;
		if(amount > 0)
		{	
			var helperName = DatabaseHelper.getGamerTag(); 
			var userId = GAConfigurations.getRecordID();
			
			var temp = {"name":helperName,"userid":userId,"amount": amount,"actiontype":kNeighborActionType.kNeighborActionTypeCollectCoinOrTrash};
			giftJSON1 = JSON.stringify(temp);
		}
		if(this._hasStolenCustomers)
		{
			this._hasStolenCustomers = false;
			var helperName = DatabaseHelper.getGamerTag(); 
			var userId = GAConfigurations.getRecordID();
			this._stolenCustomers = AVATAR_STEAL_COUNT;
			var temp = {"name":helperName,"userid":userId,"amount": AVATAR_STEAL_COUNT,"actiontype":kNeighborActionType.kNeighborActionTypeStealCustomers};
			giftJSON2 = JSON.stringify(temp);
		}
		if(giftJSON1 && giftJSON2)
		{
			finalGiftJSON = JSON.stringify({"data":[giftJSON1,giftJSON2]});	
		}
		
		if(giftJSON1 && !giftJSON2)
		{
			finalGiftJSON = JSON.stringify({"data":[giftJSON1]});	
		}
		if(!giftJSON1 && giftJSON2)
		{
			finalGiftJSON = JSON.stringify({"data":[giftJSON2]});	
		}
		if(finalGiftJSON)
		{
			var gamerTag = friend.id;
			//gamerTag = "55605";	//TODO TESTING REMOVE LATER	
			var url = [];
			url.push(GAConfigurations.getURL());
			url.push("users/add_naction?unique_id=");
			url.push(gamerTag);
			url.push("&act_json="+finalGiftJSON);
			
			url = encodeURI(url.join(""));
			
			var webFetcher = new GAWebFetcher(this,30,0);
			webFetcher.tag = 3;
			webFetcher.invokeGetRequest(url);
		}
	},
	
	rewardUserForHelpingFriend: function()
	{
		//if(!DatabaseInterface._isVisitingNeighbor)
		{
			if(this._friendCoinCollectedCount > 0)
			{
				var reward = this._friendCoinCollectedCount;
				var message = GALocalizationHandler.getRelativeString(Core.Localization.getString("COINS_RECEIVED_HELPED_FRIEND"),[reward]);
				MMGameState.getCurrentUser().updateCurrency(kOperationType.kOperationAddCoins,+reward);
				var alertBox = UIFactory.getAlertBox(Core.Localization.getString("MESSAGE"), message, ["Ok"], this);
			}
		}
	},
	
	getFriendCoinCollectedCount: function()
	{
		return this._friendCoinCollectedCount;
	},
	
	getHasStolenCustomers: function()
	{
		return this._hasStolenCustomers;
	},
		
	setFriendCoinCollectedCount: function(amount)
	{
		this._friendCoinCollectedCount = this._friendCoinCollectedCount + amount;
	},
	
	resetFriendCoinCollectedCount: function()
	{
		this._friendCoinCollectedCount = 0;
	},
	
	stealFriendsCustomers: function()
	{
		if(!TutorialManager.getHasCompletedTutorial())
		{
			this._hasStolenCustomers = true;
			AvatarHandler.removeAvatar(AVATAR_STEAL_COUNT);
			MMGameLayer.getControlLayer().getTopBar().updateTopBar();
		}
		else
		{
			if(this.canStealCustomers())
			{
				var totalCustomers = AvatarHandler.getTotalNumberOfAvatars();
				var friend = MMFriendManager.getVisitingFriendObj();
				if(+totalCustomers - 2 <= MIN_AVATAR_COUNT)
				{
					var alertBox = UIFactory.getAlertBox(Core.Localization.getString("MESSAGE"), GALocalizationHandler.getRelativeString(Core.Localization.getString("LOW_CUSTOMERS_CANT_STEAL"),[friend.displayName]), ["Ok"], this);
					return;
				}
				else
				{
					var serverTime = MMGameState.getServerTime();
					var currentActions = this.getFriendStealCustomerActionState(friend.id);
					if(currentActions)
					{	
						var timeToReset = parseInt(currentActions[1]) + SECS_IN_ONE_DAY - parseInt(serverTime);
						var actionCount = +currentActions[2];
						
						if(timeToReset < 0)
						{
							actionCount = 0;
						}
						
						if(actionCount >= MAX_AVATAR_STEAL_ACTION)
						{
							var alertBox = UIFactory.getAlertBox(Core.Localization.getString("MESSAGE"),GALocalizationHandler.getRelativeString(Core.Localization.getString("CUSTOMER_STEAL_LIMIT_REACHED_ALERT"),[friend.displayName]), ["Ok"], this);
							return;
						}
						else
						{
							actionCount++;
							this.saveFriendStealCustomerActionState([""+friend.id,serverTime,actionCount]);
							this._hasStolenCustomers = true;
						}
					}
					else
					{
						this.saveFriendStealCustomerActionState([""+friend.id,serverTime,1]);
						this._hasStolenCustomers = true;
					}
					AvatarHandler.removeAvatar(AVATAR_STEAL_COUNT);
					MMGameLayer.getControlLayer().getTopBar().updateTopBar();
				}
			}
			else
			{
				var alertBox = UIFactory.getAlertBox(Core.Localization.getString("MESSAGE"), Core.Localization.getString("NOT_ENOUGH_CASH_FOR_CUSTOMER_STEALING"), ["Ok"], this);
			}
		}
	},
	
	canStealCustomers: function()
	{
		var isValidPurchase = DatabaseHelper.isValidPurchase(kCurrencyType.kCurrencyTypeCoins, 100);
		return isValidPurchase;
	},
	
	getFriendStealCustomerActionState: function(friendId)
	{
		var friendsStealCustomerActionsList = MMStorageManager.getValueFromUserDefault("actionStealCustomer");
		
		if(friendsStealCustomerActionsList)
		{
			friendsStealCustomerActionsList = friendsStealCustomerActionsList+"";

			var friendsData = friendsStealCustomerActionsList.split("|");

			var friendsArray = [];
			for(var i = 0; i < friendsData.length; i++)
			{
				friendsArray[i] = friendsData[i].split(",");
			}
			for(var i = 0; i < friendsArray.length; i++)
			{
				var friend = friendsArray[i];
				if(friend[0] == friendId)
				{
					return friend;
				}
			}
			return null;
		}
		return null;
	},
	
	saveFriendStealCustomerActionState: function(friendData)
	{
		var friendArray = friendData;
		var friendsStealCustomerActionsList = MMStorageManager.getValueFromUserDefault("actionStealCustomer");
		if(friendsStealCustomerActionsList)
		{
			friendsStealCustomerActionsList = friendsStealCustomerActionsList+"";
			var friendsData = friendsStealCustomerActionsList.split("|");
			var friendsArray = [];
			var saved = false;
			
			for(var i = 0; i < friendsData.length; i++)
			{
				friendsArray[i] = friendsData[i].split(",");
			}
			for(var i = 0; i < friendsArray.length; i++)
			{
				var friend = friendsArray[i]
				if(friend[0] == friendData[0])
				{
					friendsArray[i] = friendData;
					saved = true;
					break;
				}
			}
			if(!saved)
			{
				friendsArray.push(friendData);
				saved = true;
			}
			var temp = [];
			if(saved)
			{
				for(var i = 0; i <friendsArray.length; i++)
				{
					var tempData = friendsArray[i].join(",");
					temp.push(tempData);
				}
				var finalString = temp.join("|");
				MMStorageManager.saveToUserDefault("actionStealCustomer", finalString);
			}
		}
		else
		{
			MMStorageManager.saveToUserDefault("actionStealCustomer", friendData);
		}
	},
	
	checkAndAddStolenCustomers: function()
	{
		var alert = false;
		if(this._stolenCustomers > 0)
		{
			for(var i = 0; i < this._stolenCustomers; i++)
			{
				AvatarHandler.addRandomAvatar();
				alert = true;
			}
		}
		if(alert)
		{
			var message = GALocalizationHandler.getRelativeString(Core.Localization.getString("MY_STEALED_CUSTOMERS"),[this._stolenCustomers]);
			var alertBox = UIFactory.getAlertBox(Core.Localization.getString("MESSAGE"), message, ["ok"], this);
			this._stolenCustomers = 0;
		}
	},

	destroy: function()
	{
		this._allNeighborActions = null;
		this._friendCoinCollectedCount = 0;
		this._hasStolenCustomers = false;
		this._myStolenCustomerCount = 0;
		this._stolenCustomers = 0;
		this._allNeighborActions = null;
	}
});